package com.wing.purchase.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.area.model.response.AreaVO;
import com.wing.area.service.AreaService;
import com.wing.chanjet.entity.supplier.request.PartnerClassCreateRequest;
import com.wing.chanjet.entity.supplier.request.PartnerTypeCreateRequest;
import com.wing.chanjet.entity.supplier.request.SupplierCreateRequest;
import com.wing.chanjet.entity.supplier.response.SupplierQueryResponse;
import com.wing.chanjet.feign.ChanjetClient;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.product.service.DynamicService;
import com.wing.purchase.dao.SupplierCategoryDao;
import com.wing.purchase.dao.SupplierInfoDao;
import com.wing.purchase.model.entity.SupplierCategory;
import com.wing.purchase.model.entity.SupplierContacts;
import com.wing.purchase.model.entity.SupplierInfo;
import com.wing.purchase.model.entity.SupplierLevel;
import com.wing.purchase.model.request.SupplierDetailExcelInForm;
import com.wing.purchase.model.request.SupplierInfoForm;
import com.wing.purchase.model.response.SupplierInfoVO;
import com.wing.sell.dao.CustomersInfoDao;
import com.wing.sell.model.entity.CustomersInfo;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 供应商表-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class SupplierInfoServiceImpl extends ServiceImpl<SupplierInfoDao, SupplierInfo> implements SupplierInfoService {

    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private SupplierContactsService supplierContactsService;
    @Autowired
    ChanjetClient chanjetClient;
    @Autowired
    SupplierCategoryDao supplierCategoryDao;

    @Override
    public int add(SupplierInfoForm supplierInfoForm) {
        //校验
        SupplierInfo supplierInfo =new SupplierInfo();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(SupplierInfo.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(supplierInfoForm, supplierInfo, copyOptions);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        String code=dynamicService.getDayNextCode("pur_supplier_info");
        String day=simpleDateFormat.format(new Date());
    /*    supplierInfo.setCode("G"+day+code);*/
        supplierInfo.setDay(Long.valueOf(day));
        supplierInfo.setNo(Long.valueOf(code));

        try {
            String cjtSupplierId = updateAndSaveCjtSupplier(supplierInfoForm,"add");
            supplierInfo.setCjtId(cjtSupplierId);
        }catch (Exception e){
             log.info("新增畅捷通对用供应商出现异常"+e);
             throw new BusinessException("新增畅捷通对用供应商出现异常");
        }

        return baseMapper.insert(supplierInfo);
    }

    @Override
    public List<SupplierInfoVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<SupplierInfoVO> pageList4app(Page page, Map<String, Object> params) {
        List<SupplierInfoVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public SupplierInfoVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public SupplierInfoVO getCustomerInfo(Long subjectId, Long contactsId) {
        SupplierInfoVO supplierInfo = baseMapper.get4appById(subjectId);
        SupplierContacts supplierContacts = supplierContactsService.getById(contactsId);
        supplierInfo.setContactsName(supplierContacts.getContactName());
        supplierInfo.setContactsPhone(supplierContacts.getPhoneNumber());
        return supplierInfo;
    }

    @Autowired
    SupplierCategoryService supplierCategoryService;

    @Autowired
    SupplierLevelService supplierLevelService;

    @Autowired
    private AreaService areaService;

    @Autowired
    CustomersInfoDao customersInfoDao;

    @Override
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String[] headerArr = {"供应商公司名称","供应商编码","供应商级别","供应商分类","证件号码","收款银行","收款银行账户","收款银行账号","省","市","区/县","联系地址","业务联系人","财务联系人","法定代表人","备注"};
        List<String[]> downData = new ArrayList<>();
        List<String> indexArr = new ArrayList<>();


        //供应商级别
        Page<SupplierLevel> pg2 = new Page<>(1, 999);
        QueryWrapper<SupplierLevel> queryWrapper2 = new QueryWrapper<>();

        IPage<SupplierLevel> list2 = supplierLevelService.getBaseMapper().selectPage(pg2, queryWrapper2);
        List<SupplierLevel> supplierLevelList = list2.getRecords();
        String[] supplierLevelData = new String[]{supplierLevelList.stream().map(t -> t.getName()).collect(Collectors.joining(","))};
        indexArr.add("2");
        downData.add(supplierLevelData);

        //供应商分类
        Page<SupplierCategory> pg = new Page<>(1, 999);
        QueryWrapper<SupplierCategory> queryWrapper = new QueryWrapper<>();
        IPage<SupplierCategory> list = supplierCategoryService.getBaseMapper().selectPage(pg, queryWrapper);
        List<SupplierCategory> supplierCategoryList = list.getRecords();
        String[] natureData = new String[]{supplierCategoryList.stream().map(t -> t.getName()).collect(Collectors.joining(","))};
        indexArr.add("3");
        downData.add(natureData);

        // 获取所有省份
        List<AreaVO> provinceList = areaService.getProvinceList();

        // 将省份名称加入downData，并为省份列添加索引
        String provinces = provinceList.stream().map(AreaVO::getName).collect(Collectors.joining(","));
        downData.add(new String[]{provinces});
        indexArr.add("8"); // 省份列索引

        // 假设每个省份和城市都有唯一的ID，这里需要构建一个映射关系，用于后续查找2222222
   /*     Map<Integer, List<AreaVO>> provinceToCitiesMap = new HashMap<>();
        for (AreaVO province : provinceList) {
            List<AreaVO> cityList = areaService.getCityList(province.getId()); // 根据省份ID获取城市列表
            provinceToCitiesMap.put(province.getId(), cityList);
            String[] cityData = new String[]{cityList.stream().map(t -> t.getName()).collect(Collectors.joining(","))};
            downData.add(cityData);

            for (AreaVO city : cityList) {
                List<AreaVO> areaList = areaService.getAreaList(city.getId()); // 根据城市ID获取区/县列表
                // 为简化，直接将区/县名称添加到downData中
                String[] areaData = new String[]{areaList.stream().map(t -> t.getName()).collect(Collectors.joining(","))};
                downData.add(areaData);
            }
        }

        // 添加城市和区/县的索引（这里假设城市和区/县共用同一列）
        indexArr.add("8"); // 城市列索引
        indexArr.add("9"); // 区/县列索引*/



        DownExcelUtil.createExcelTemplate(response, request, "供应商导入模板", Arrays.asList(headerArr), downData, indexArr);
    }


    @Override
    public JsonResult importExcel(List<SupplierDetailExcelInForm> list) {

        int i = 1;
        for (SupplierDetailExcelInForm supplierDetailExcelInForm : list) {
            if (StringUtils.isBlank(supplierDetailExcelInForm.getCode())) {
                throw new BusinessException(300, "第" + i + "行【供应商编码】未输入数据");
            }
            if (StringUtils.isBlank(supplierDetailExcelInForm.getCorporateName())) {
                throw new BusinessException(300, "第" + i + "行【供应商名称】未输入数据");
            }
            if (StringUtils.isBlank(supplierDetailExcelInForm.getLevelId())) {
                throw new BusinessException(300, "第" + i + "行【供应商级别】未输入数据");
            }
            if (StringUtils.isBlank(supplierDetailExcelInForm.getCategoryId())) {
                 throw new BusinessException(300, "第" + i + "行【供应商分类】未输入数据");
            }
            if (StringUtils.isBlank(supplierDetailExcelInForm.getCertificateNumber())) {
                throw new BusinessException(300, "第" + i + "行【证件号码】未输入数据");
            }
            SupplierInfo supplierInfo =new SupplierInfo();

            //供应商级别
            Page<SupplierLevel> pg2 = new Page<>(1, 999);
            QueryWrapper<SupplierLevel> queryWrapper2 = new QueryWrapper<>();

            IPage<SupplierLevel> list2 = supplierLevelService.getBaseMapper().selectPage(pg2, queryWrapper2);
            List<SupplierLevel> supplierLevelList = list2.getRecords();
            SupplierLevel result1 = supplierLevelList.stream()
                    .filter(provinces -> provinces.getName().equals(supplierDetailExcelInForm.getLevelId()))
                    .findFirst()
                    .orElse(null);
             if(result1!=null){
                 supplierInfo.setLevelId(Long.valueOf(result1.getId()));
             }


            //供应商分类
            Page<SupplierCategory> pg = new Page<>(1, 999);
            QueryWrapper<SupplierCategory> queryWrapper = new QueryWrapper<>();
            IPage<SupplierCategory> list3 = supplierCategoryService.getBaseMapper().selectPage(pg, queryWrapper);
            List<SupplierCategory> supplierCategoryList = list3.getRecords();
            SupplierCategory result3 = supplierCategoryList.stream()
                    .filter(provinces -> provinces.getName().equals(supplierDetailExcelInForm.getCategoryId()))
                    .findFirst()
                    .orElse(null);
            if(result3!=null){
                supplierInfo.setCategoryId(Long.valueOf(result3.getId()));
            }


            List<AreaVO> provinceList = areaService.getProvinceList();
            AreaVO result2 = provinceList.stream()
                    .filter(provinces -> provinces.getName().equals(supplierDetailExcelInForm.getProvinceId()))
                    .findFirst()
                    .orElse(null);

            if(result2!=null){
                List<AreaVO> cityList = areaService.getCityList(result2.getId()); // 根据省份ID获取城市列表
                AreaVO cityResult = cityList.stream()
                        .filter(citys -> citys.getName().equals(supplierDetailExcelInForm.getCityId()))
                        .findFirst()
                        .orElse(null);

                if(cityResult!=null){
                    supplierInfo.setProvinceId(Long.valueOf(cityResult.getId()));
                    if(cityResult!=null){
                        supplierInfo.setCityId(Long.valueOf(cityResult.getId()));
                    }

                    List<AreaVO> areaVOList = areaService.getAreaList(result2.getId()); // 根据省份ID获取城市列表
                    AreaVO areaVO = areaVOList.stream()
                            .filter(areas -> areas.getName().equals(supplierDetailExcelInForm.getAreaId()))
                            .findFirst()
                            .orElse(null);

                    if(areaVO!=null){
                        supplierInfo.setAreaId(Long.valueOf(areaVO.getId()));
                    }

                }
            }

            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(SupplierInfo.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(supplierDetailExcelInForm, supplierInfo, copyOptions);
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
            String code=dynamicService.getDayNextCode("pur_supplier_info");
            String day=simpleDateFormat.format(new Date());
            supplierInfo.setCode(supplierDetailExcelInForm.getCode());
            supplierInfo.setDay(Long.valueOf(day));
            supplierInfo.setNo(Long.valueOf(code));
            if(result2!=null){
                supplierInfo.setProvinceId(Long.valueOf(result2.getId()));
            }
            supplierInfo.setSourceType(SupplierInfo.SourceType.backstage);
            supplierInfo.setStatus(SupplierInfo.Status.pass);

            SupplierInfoForm supplierInfoForm=new SupplierInfoForm();
            supplierInfoForm.setCode(supplierInfo.getCode());
            supplierInfoForm.setCorporateName(supplierInfo.getCorporateName());
            supplierInfoForm.setCategoryId(supplierInfo.getCategoryId());
            updateAndSaveCjtSupplier(supplierInfoForm,"add");

            baseMapper.insert(supplierInfo);
        }
        return null;
    }

    @Override
    public JsonResult getSupplierList() {
        JsonResult<List<SupplierQueryResponse>> supplierList = chanjetClient.getSupplierList();
        List<SupplierQueryResponse> supplierListData = supplierList.getData();
        for (SupplierQueryResponse supplierListDatum : supplierListData) {
            //校验
            SupplierInfo supplierInfo =new SupplierInfo();
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(SupplierInfo.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(supplierListDatum, supplierInfo, copyOptions);
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
            String code=dynamicService.getDayNextCode("pur_supplier_info");
            String day=simpleDateFormat.format(new Date());
            /*    supplierInfo.setCode("G"+day+code);*/
            supplierInfo.setDay(Long.valueOf(day));
            supplierInfo.setNo(Long.valueOf(code));

            supplierInfo.setCorporateName(supplierListDatum.getName());
            supplierInfo.setCode(supplierListDatum.getCode());
            supplierInfo.setSourceType(SupplierInfo.SourceType.backstage);
            supplierInfo.setStatus(SupplierInfo.Status.pending);
            supplierInfo.setCjtId(supplierListDatum.getID());
            supplierInfo.setPartnerTypeName(supplierListDatum.getPartnerTypeName());

            LambdaQueryWrapper<SupplierInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SupplierInfo::getCjtId,supplierListDatum.getID());
            SupplierInfo supplierInfo1 = baseMapper.selectOne(lambdaQueryWrapper);
            if(supplierInfo1!=null){
                SupplierInfo supplierInfo2 =new SupplierInfo();
                BeanUtil.copyProperties(supplierListDatum, supplierInfo2, copyOptions);
                supplierInfo2.setId(supplierInfo1.getId());
                baseMapper.updateById(supplierInfo1);
            }else{
                baseMapper.insert(supplierInfo);
            }



            //属于客户类型的保存到对应客户表
            if(supplierListDatum.getPartnerTypeName().equals("客户")){
                CustomersInfo customersInfo = new CustomersInfo();
                CopyOptions copyOptions2 = CopyOptions.create()
                        .setEditable(CustomersInfo.class)
                        .setIgnoreError(true)
                        .setIgnoreNullValue(true);
                BeanUtil.copyProperties(supplierListDatum, customersInfo, copyOptions2);
                customersInfo.setCreator(JwtUtils.getLoginUserId());
                customersInfo.setCreatorName(JwtUtils.getLoginUsername());
                customersInfo.setCreateTime(LocalDateTime.now());
                customersInfo.setCompanyInfoId(JwtUtils.getEnterpriseId());
                customersInfo.setCustomerType(CustomersInfo.CustomerType.formal);
                customersInfo.setCustomerName(supplierListDatum.getName());
                customersInfo.setCode(supplierListDatum.getCode());


                LambdaQueryWrapper<CustomersInfo> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper2.eq(CustomersInfo::getCode,supplierListDatum.getCode());
                CustomersInfo customersInfo1 = customersInfoDao.selectOne(lambdaQueryWrapper2);
                if(customersInfo1!=null){
                    CustomersInfo customersInfo2 =new CustomersInfo();
                    BeanUtil.copyProperties(supplierListDatum, customersInfo2, copyOptions);
                    customersInfo2.setId(supplierInfo1.getId());
                    customersInfoDao.updateById(customersInfo2);
                }else{
                    customersInfoDao.insert(customersInfo);
                }
            }

        }
         return JsonResult.success();
    }

    @Override
    public String updateAndSaveCjtSupplier(SupplierInfoForm supplierInfoForm,String operateType) {
        try {
            //新增到畅捷通那边   同时根据分类id categoryId 查询对应分类编码  supplier_number
            LambdaQueryWrapper<SupplierCategory> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.eq(SupplierCategory::getId,supplierInfoForm.getCategoryId());
            SupplierCategory supplierCategory1 = supplierCategoryDao.selectOne(lambdaQueryWrapper2);
            if(supplierCategory1!=null && supplierCategory1.getSupplierNumber()!=null){
                SupplierCreateRequest supplierCreateRequest=new SupplierCreateRequest();
                supplierCreateRequest.setCode(supplierInfoForm.getCode());
                supplierCreateRequest.setName(supplierInfoForm.getCorporateName());
                if(operateType.equals("edit")){
                    supplierCreateRequest.setID(supplierCategory1.getCjtId());
                    chanjetClient.updateSupplier(supplierCreateRequest);

                }else{
                    PartnerClassCreateRequest partnerClassCreateRequest=new PartnerClassCreateRequest();
                    partnerClassCreateRequest.setCode(supplierCategory1.getSupplierNumber());
                    supplierCreateRequest.setPartnerClass(partnerClassCreateRequest);
                    PartnerTypeCreateRequest partnerTypeCreateRequest=new PartnerTypeCreateRequest();
                    partnerTypeCreateRequest.setCode("00");
                    supplierCreateRequest.setPartnerType(partnerTypeCreateRequest);
                    JsonResult supplier = chanjetClient.createSupplier(supplierCreateRequest);
                    if(StringUtils.isNotEmpty(supplier.getMsg())){
                        String msg=supplier.getMsg();
                        return msg;
                    }
                }
            }
        }catch (Exception e){
            log.info("新增畅捷通对用供应商出现异常"+e);
            throw new BusinessException("新增畅捷通对用供应商出现异常");
        }

        return "";
    }


}
